package vip.xiaonuo.facedoor.modular.workflow.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.ClassPath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.pojo.base.entity.ProcessBaseEntity;
import vip.xiaonuo.facedoor.modular.workflow.entity.WorkflowSetting;
import vip.xiaonuo.facedoor.modular.workflow.mapper.WorkflowSettingMapper;
import vip.xiaonuo.facedoor.modular.workflow.service.WorkflowSettingService;
import vip.xiaonuo.facedoor.modular.workflow.vo.WorkFlowBeanInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class WorkflowSettingServiceImpl extends ServiceImpl<WorkflowSettingMapper, WorkflowSetting> implements WorkflowSettingService {

    @Override
    public List<WorkflowSetting> listWorkflowSetting() {
        // 1、 查询工作流系统的数据，如果本地数据库没有，新增至数据库

        return this.list();
    }

    @Override
    public List<WorkFlowBeanInfo> WorkFlowBizEntity() {
        List<String> packages = new ArrayList<>();
        packages.add("vip.xiaonuo.workflow.modular");
        return findSubClasses(packages, ProcessBaseEntity.class);
    }

    private static List<WorkFlowBeanInfo> findSubClasses(List<String> packages, Class<?> parentClass) {
        List<WorkFlowBeanInfo> result = new ArrayList<>();
        for(String packageName : packages){
            try{
                ClassPath classPath = ClassPath.from(ClassLoader.getSystemClassLoader());
                ImmutableSet<ClassPath.ClassInfo> classes = classPath.getTopLevelClassesRecursive(packageName);
                for (ClassPath.ClassInfo classInfo : classes){
                    Class<?> clazz = Class.forName(classInfo.getName());
                    if(parentClass.isAssignableFrom(clazz)){
                        result.add(new WorkFlowBeanInfo(clazz));
                    }
                }
            }catch (IOException | ClassNotFoundException e){
                log.info(e.getMessage());
            }
        }

        return result;
    }


}
